
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * This thread gets orders from the database periodically and transmits them to the
 * TransmitOrderThread, which will transmit them directly to the client.
 * 
 * @author Alexandre Dos Santos Coelho
 */
public class OrderThread extends Thread {

  private Server server; // Attached server
  private int delay; // Delay between two queries on the Order table
  private boolean running = true; // Determines if thread is running
  private TransmitOrderThread transmitOrderThread;

  /**
   * Constructor. Creates and lauches the thread
   * @param s Attached server
   * @param d Delay betweeen two queries on the Order database table
   */
  public OrderThread(Server s, int d) {
    server = s;
    delay = d;
    transmitOrderThread = new TransmitOrderThread(server, delay);
    this.start();
  }

  /**
   * Tread run method. Gets periodically orders from the database table and transmits them
   * to the TransmitOrderThread
   */
  @Override
  public void run() {
    while (running) {
      try {
        Thread.sleep((long) (delay * 1000));
        ResultSet rs = server.getDataManager().getOrders();

        // Constructing orders
        while (rs!=null && rs.next()) {
          int id = rs.getInt("id");
          int userId = rs.getInt("user_id");
          String machineId = rs.getString("machine_id");
          String order = rs.getString("order");
          Order o = new Order(id, userId, machineId, order);
          transmitOrderThread.addOrder(o); // Adding in transmit thread
        }

      } catch (SQLException ex) {
      } catch (InterruptedException ex) {
      }
    }
  }
}
